var Modal = require("./modal.js")
var Login = require("./login.js")
var app = getApp()
function ajax(url, method, data, isAsync, success_callback, error_callback) {
  wx.request({
    url: app.serverUrl + url,
    method: method,
    header: {
      "content-type": "application/json",
      "sessionid": app.globalData.sessionid
    },
    data: data,
    success: function (res) {
      if (res.data.code==null||res.data.code != 0) {
        if(res.data.code==100){
          Login.login(()=>{
            ajax(url, method, data, isAsync, success_callback, error_callback);
          });
        }else{
          Modal.showErr(res.data.msg);
          if (error_callback) error_callback(res.data.msg);
        }
      } else {
        if (success_callback) success_callback(res.data);
      }
    }
  });
}

function doPost(url, data, isAsync, success_callback, error_callback) {
  ajax(url, "post", data, isAsync, success_callback, error_callback);
}

function doGet(url, data, isAsync, success_callback, error_callback) {
  ajax(url, "get", data, isAsync, success_callback, error_callback);
}

function doPut(url, data, isAsync, success_callback, error_callback) {
  ajax(url, "put", data, isAsync, success_callback, error_callback);
}

function doDelete(url, data, isAsync, success_callback, error_callback) {
  ajax(url, "delete", data, isAsync, success_callback, error_callback);
}

class Ajax {
  static AsyncPost(url, data, success_callback, error_callback) {
    doPost(url, data, true, success_callback, error_callback);
  }
  static AsyncGet(url, data, success_callback, error_callback) {
    doGet(url, data, true, success_callback, error_callback);
  }
  static AsyncPut(url, data, success_callback, error_callback) {
    doPut(url, data, true, success_callback, error_callback);
  }
  static AsyncDelete(url, data, success_callback, error_callback) {
    doDelete(url, data, true, success_callback, error_callback);
  }
  static SyncPost(url, data, success_callback, error_callback) {
    doPost(url, data, false, success_callback, error_callback);
  }
  static SyncGet(url, data, success_callback, error_callback) {
    doGet(url, data, false, success_callback, error_callback);
  }
  static AsyncPut(url, data, success_callback, error_callback) {
    doPut(url, data, false, success_callback, error_callback);
  }
  static AsyncDelete(url, data, success_callback, error_callback) {
    doDelete(url, data, false, success_callback, error_callback);
  }
}

module.exports=Ajax